#ifndef _RESOURCE_DOWNLOAD_3CACD5C1_2509_41B5_A233_CDECAC08C51A_
#define _RESOURCE_DOWNLOAD_3CACD5C1_2509_41B5_A233_CDECAC08C51A_
#pragma once
#include "base/threading/thread.h"
#include "base/threading/non_thread_safe.h"
#include "resource_request_context.h"
#include "work_thread.h"
#include "url_defines.h"
#include "work_channel.h"

namespace dl {

typedef scoped_refptr<net::IOBuffer> IOBufferPtr;

/**
 * 资源下载封装
 */
class ResourceDownload : public net::URLRequest::Delegate,
                         public base::NonThreadSafe {
public:
  struct ResponseDelegate {
    /**
    * URL请求开始回复
    * @param symbol指示请求的编号
    */
    virtual bool OnResponseStarted(unsigned int symbol, ResponsePtr response) = 0;
    /**
    * 网络数据读取完成通知
    * @param symbol指示请求的编号
    * @param buffer指示数据缓冲区
    */
    virtual void OnReadCompleted(unsigned int symbol, IOBufferWithSizePtr buffer) = 0;
    /**
     * 请求事务结束
     * @param symbol指示请求的编号
     * @param stat表示URL请求状态
     */
    virtual void OnResponseFinished(unsigned int symbol, net::URLRequestStatus stat) = 0;
  };

public:
  explicit ResourceDownload(ResponseDelegate* delegate);
  ~ResourceDownload();

  /**
   * 请求下载资源
   * @param symbol指示此条请求的编号
   * @param data表示请求的信息
   */
  void AddUrlRequest(unsigned int symbol, const URLRequestData& data);
  /**
   * 取消下载请求
   * @param symbol指示此条请求的编号
   */
  void CancelUrlRequest(unsigned int symbol);

private:
  // URLRequest::Delegate接口
  virtual void OnReceivedRedirect(net::URLRequest* request, const GURL& new_url, bool* defer_redirect);
  virtual void OnAuthRequired(net::URLRequest* request, net::AuthChallengeInfo* auth_info);
  virtual void OnCertificateRequested(net::URLRequest* request, net::SSLCertRequestInfo* cert_request_info);
  virtual void OnSSLCertificateError(net::URLRequest* request, const net::SSLInfo& ssl_info, bool fatal);
  virtual void OnResponseStarted(net::URLRequest* request);
  virtual void OnReadCompleted(net::URLRequest* request, int bytes_read);
  // 下载结束通知
  void OnResponseCompleted(net::URLRequest* request);
  // 取消下载
  void CancelRequest(net::URLRequest* request);
  bool CompleteStarted(net::URLRequest* request);
  void CompleteRead(net::URLRequest* request, int bytes_read);

private:
  typedef std::map<unsigned int, net::URLRequest*> IDRequestMap;
  IDRequestMap requests_;
  ResponseDelegate* delegate_;
  scoped_ptr<ResourceRequestContext> context_;
};

}

#endif//_RESOURCE_DOWNLOAD_3CACD5C1_2509_41B5_A233_CDECAC08C51A_